<?php

class WebUser extends CWebUser{

    protected $_model;

	public $loginUrl = array('user/login');

	public function init() {
		$conf = Yii::app()->session->cookieParams;
        $this->identityCookie = array(
            'path' => $conf['path'],
            'domain' => $conf['domain'],
        );
        parent::init();
	}

    function isAdmin(){
        $user = $this->loadUser(Yii::app()->user->id);
		return $user->user_type == 'A';
    }

	function getFirstName(){
		$user = $this->loadUser(Yii::app()->user->id);
		return !empty($user) ? $user->name : '';
	}
	
	function countNotification() {
		$user = $this->loadUser(Yii::app()->user->id);
		
		return $user->countNotification();
	}

	function addNotification($type, $message, $key = null, $title = '') {
		if ( $key === null ) $key = md5(microtime().rand(9999, 99999));

		if ( empty($title) ) {
			switch ($type) {
				case 'E':
					$title = t('error');
					break;
				case 'W':
					$title = t('warning');
					break;
				case 'N':
					$title = t('notice');
					break;
			}
		}

		$flash = "$type#$message#$title";
		$this->setFlash($key, $flash);
	}

	function addNotifications($type, $errors, $key = null, $title = '') {

		if ( !empty($errors) ) {
			$error_messages = array();
			foreach ($errors as $error_field => $error) {
				if ( is_array($error) ) {
					$error_messages[] = ' - ' . implode('<br /> - ', $error);
				}
			}
			$error_message = implode('<br />', $error_messages);
			$this->addNotification($type, $error_message, $key, $title);
		}

	}

	function getNotification($key, $defaultValue = null, $delete = true) {
		$flash = $this->getFlash($key, $defaultValue, $delete = true);

		list($type, $message, $title) = explode('#', $v);

		return array(
			'key' => $key,
			'type' => $type,
			'message' => $message,
			'title' => $title,
		);
	}

	function getNotifications($delete = true) {
		$_flashes = $this->getFlashes($delete);

		$flashes = array();
		foreach ($_flashes as $k => $v ) {
			list($type, $message, $title) = explode('#', $v);

			$flashes[$k] = array(
				'key' => $k,
				'type' => $type,
				'message' => $message,
				'title' => $title,
			);
		}

		return $flashes;
	}

    // Load user model.
    protected function loadUser($user_id=null)
    {
        if($this->_model===null)
        {
            if($user_id!==null)
                $this->_model=User::model()->findByPk($user_id);

			if ( $this->_model === null ) {
				$result = idApi('getUserInfo', array('user_id' => $user_id));
				if ( $result['success'] ) {
					$userdata = $result['user_data'];
					
					$model = User::model();
					$model->attributes = $userdata;
					$model->user_id = $user_id;
					$model->isNewRecord = true;

					$model->no_update_to_ID = true;
					$model->save(false);
					$this->_model = $model;
				}
			}
        }
        return $this->_model;
    }
}